// src/components/TimeRangeSelector.tsx
import React, { useEffect, useRef, useCallback } from 'react';
import { Button, Card, Typography, Space, message, Modal, Input } from 'antd';
import { ClearOutlined, CalendarOutlined } from '@ant-design/icons';
import moment from 'moment';
import { useTimeSlotStore } from '../stores/useTimeSlotStore'; // 引入 Zustand Store

const { Title, Text } = Typography;
const { TextArea } = Input;

const TimeRangeSelector: React.FC = () => {
  const gridRef = useRef<HTMLDivElement>(null);

  // 从 Zustand Store 获取状态和方法
  const {
    timeSlots,
    isSelecting,
    selectedRange,
    initialized,
    selectedReason,
    showReasonModal,
    reasonText,
    initializeTimeSlots,
    updateExpiredStatus,
    startSelection,
    updateTemporarySelection,
    endSelection,
    clearSelection,
    closeReasonModal,
    updateReasonText,
    saveReason
  } = useTimeSlotStore();

  // 初始化数据 + 定时更新过期状态
  useEffect(() => {
    if (!initialized) {
      initializeTimeSlots();
    }

    // 每小时更新一次过期状态
    const interval = setInterval(() => {
      updateExpiredStatus();
    }, 3600000);

    return () => clearInterval(interval);
  }, [initialized, initializeTimeSlots, updateExpiredStatus]);

  // 处理开始选择（点击时间段方块）
  const handleStartSelect = useCallback((slotId: string) => {
    const { valid, slot } = startSelection(slotId);

    // 若时间段无效（过期/被他人选择）
    if (!valid) {
      const targetSlot = timeSlots.find(s => s.id === slotId);
      if (targetSlot?.isExpired) {
        message.warning('无法选择已过时的时间段');
      } else if (targetSlot?.isSelectedByOthers) {
        message.warning('该时间段已被他人选择');
      }
      return;
    }

    // 若已在选择中，触发结束选择
    if (isSelecting && slot) {
      const { success, range } = endSelection(slotId);
      if (success && range) {
        message.success(
          `选择成功: ${range.start.format('MM-DD HH:mm')} 至 ${range.end.format('MM-DD HH:mm')}`
        );
      } else {
        message.warning('选择范围包含不可用的时间段，请重新选择');
      }
    } else if (slot) {
      // 新开始选择，提示用户
      message.info(`开始选择: ${slot.date.format('MM-DD HH:mm')}`);
    }
  }, [isSelecting, timeSlots, startSelection, endSelection]);

  // 处理滑动预览（鼠标进入时间段方块）
  const handleMouseMove = useCallback((slotId: string) => {
    updateTemporarySelection(slotId);
  }, [updateTemporarySelection]);

  // 处理原因填写框的「确定」按钮
  const handleReasonConfirm = () => {
    const success = saveReason();
    if (success) {
      message.success('原因提交成功');
    } else {
      message.warning('请填写选择时间段的原因');
    }
  };

  // 获取7天日期列表（横向显示）
  const getUniqueDates = () => {
    const dates = new Map<string, moment.Moment>();
    timeSlots.forEach(slot => {
      const dateStr = slot.date.format('YYYY-MM-DD');
      if (!dates.has(dateStr)) dates.set(dateStr, slot.date);
    });
    return Array.from(dates.values());
  };

  // 获取小时标签列表（顶部显示，00:00 至 23:00）
  const getHourLabels = () => {
    return Array.from({ length: 24 }, (_, i) => 
      `${i.toString().padStart(2, '0')}:00`
    );
  };

  // 获取每小时的两个半小时时间段（0分和30分）
  const getHalfHourSlotsForHour = (hour: number) => [
    { hour, minute: 0 },
    { hour, minute: 30 }
  ];

  // 加载中状态
  if (!initialized) {
    return <div style={{ margin: 20 }}>加载时间段数据中...</div>;
  }

  const uniqueDates = getUniqueDates();
  const hourLabels = getHourLabels();

  return (
    <Card 
      title={
        <Space>
          <CalendarOutlined />
          <Title level={5} style={{ margin: 0 }}>7天时间段选择器</Title>
        </Space>
      }
      extra={
        <Button 
          icon={<ClearOutlined />} 
          onClick={clearSelection}
          disabled={!selectedRange.start || !selectedRange.end}
        >
          清除选择
        </Button>
      }
      style={{ margin: 20, width: '100%' }}
    >
      {/* 选择结果与原因显示 */}
      {(selectedRange.start && selectedRange.end) && (
        <div style={{ marginBottom: 16, padding: 8, backgroundColor: '#f5f5f5', borderRadius: 4 }}>
          <Text strong>当前选择:</Text>
          <Text> {selectedRange.start.format('MM-DD HH:mm')} 至 {selectedRange.end.format('MM-DD HH:mm')}</Text>
          <Text> (共 {(selectedRange.end.diff(selectedRange.start, 'minutes') / 60).toFixed(1)} 小时)</Text>
          {selectedReason && (
            <div style={{ marginTop: 8 }}>
              <Text strong>选择原因:</Text>
              <Text style={{ marginLeft: 8 }}>{selectedReason}</Text>
            </div>
          )}
        </div>
      )}

      {/* 时间段选择网格 */}
      <div 
        ref={gridRef}
        style={{ 
          overflowX: 'auto',
          overflowY: 'auto',
          maxHeight: 500,
          border: '1px solid #e8e8e8',
          borderRadius: 4,
          width: '100%'
        }}
      >
        {/* 顶部小时标签行 */}
        <div style={{ display: 'flex' }}>
          {/* 左上角标题（时间/日期） */}
          <div style={{ 
            width: 100,
            minWidth: 100,
            flexShrink: 0,
            height: 40, 
            display: 'flex', 
            alignItems: 'center', 
            justifyContent: 'center',
            fontWeight: 'bold',
            borderBottom: '1px solid #e8e8e8',
            borderRight: '1px solid #e8e8e8',
            backgroundColor: '#fafafa'
          }}>
            时间/日期
          </div>

          {/* 小时标签（00:00 至 23:00） */}
          {hourLabels.map((hourLabel, hourIndex) => (
            <div key={hourIndex} style={{ 
              flex: 1,
              minWidth: 40,
              height: 40, 
              display: 'flex', 
              alignItems: 'center', 
              justifyContent: 'center',
              borderBottom: '1px solid #e8e8e8',
              borderRight: '1px solid #e8e8e8',
              fontSize: 12,
              backgroundColor: '#fafafa',
              fontWeight: 'bold'
            }}>
              {hourLabel}
            </div>
          ))}
        </div>

        {/* 左侧日期 + 右侧时间段方块 */}
        {uniqueDates.map((date, dateIndex) => (
          <div key={dateIndex} style={{ display: 'flex' }}>
            {/* 左侧日期标签 */}
            <div style={{ 
              width: 100,
              minWidth: 100,
              flexShrink: 0,
              height: 50,
              display: 'flex', 
              alignItems: 'center', 
              justifyContent: 'center',
              borderBottom: '1px solid #e8e8e8',
              borderRight: '1px solid #e8e8e8',
              fontWeight: 'bold',
              backgroundColor: '#fafafa'
            }}>
              <div style={{ textAlign: 'center' }}>
                <div>{date.format('MM-DD')}</div>
                <div style={{ fontSize: 12 }}>
                  {['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.day()]}
                </div>
              </div>
            </div>

            {/* 右侧时间段方块（每小时分两个30分钟块） */}
            {hourLabels.map((hourLabel, hourIndex) => {
              const hour = parseInt(hourLabel.split(':')[0], 10);
              const halfHourSlots = getHalfHourSlotsForHour(hour);

              return (
                <div key={hourIndex} style={{ flex: 1, minWidth: 40, display: 'flex' }}>
                  {halfHourSlots.map(({ minute }, minuteIndex) => {
                    const slotId = `${date.format('YYYYMMDD')}${
                      hour.toString().padStart(2, '0')
                    }${minute.toString().padStart(2, '0')}`;
                    const slot = timeSlots.find(s => s.id === slotId);

                    // 方块样式（根据状态区分颜色）
                    let bgColor = '#fff';
                    let cursor = 'pointer';
                    if (slot?.isExpired) {
                      bgColor = '#f0f0f0';
                      cursor = 'not-allowed';
                    } else if (slot?.isSelectedByOthers) {
                      bgColor = '#f5222d'; // 他人选择：红色
                      cursor = 'not-allowed';
                    } else if (slot?.isSelected) {
                      bgColor = '#1890ff'; // 自己选择：蓝色
                    } else if (slot?.isTemporary) {
                      bgColor = '#40a9ff'; // 临时预览：浅蓝色
                    }

                    // 边框样式（同一小时内用虚线分隔）
                    const borderRight = minuteIndex === 1 
                      ? '1px solid #e8e8e8' 
                      : '1px dashed #e0e0e0';

                    return (
                      <div
                        key={`${hourIndex}-${minuteIndex}`}
                        id={slotId}
                        style={{ 
                          flex: 1,
                          height: 50,
                          borderBottom: '1px solid #e8e8e8',
                          borderRight: borderRight,
                          backgroundColor: bgColor,
                          cursor: cursor,
                          transition: 'background-color 0.2s',
                          opacity: slot?.isExpired ? 0.6 : 1,
                          minWidth: 20
                        }}
                        onClick={() => handleStartSelect(slotId)}
                        onMouseEnter={() => handleMouseMove(slotId)}
                      />
                    );
                  })}
                </div>
              );
            })}
          </div>
        ))}
      </div>

      {/* 使用说明 */}
      <div style={{ marginTop: 16, fontSize: 12, color: '#666' }}>
        <Text>提示: 点击第一个方块作为开始，滑动鼠标预览选择范围，点击第二个方块作为结束完成选择。</Text>
        <br />
        <Text type="warning">红色方块表示已被他人选择，灰色方块表示已过时，这些时间段不可选择。</Text>
        <br />
        <Text type="primary">蓝色方块表示您当前选择的时间段。表格宽度会根据父容器自适应，窄屏时可横向滚动。</Text>
      </div>

      {/* 原因填写模态框（选择完成后弹出） */}
      <Modal
        title="填写选择原因"
        open={showReasonModal}
        onCancel={closeReasonModal}
        onOk={handleReasonConfirm}
        maskClosable={false}
        destroyOnClose
      >
        <Text type="info" style={{ display: 'block', marginBottom: 8 }}>
          请填写选择该时间段的原因（必填）：
        </Text>
        <TextArea
          value={reasonText}
          onChange={(e) => updateReasonText(e.target.value)}
          placeholder="例如：项目会议、设备维护..."
          rows={4}
          maxLength={200}
          showCount
        />
      </Modal>
    </Card>
  );
};

export default TimeRangeSelector;